<template>
  <div>
    <div>
      <table class="table table-bordered vertical-align-middle text-center">
        <colgroup>
          <col width="16%" />
          <col width="34%" />
          <col width="16%" />
          <col width="34%" />
        </colgroup>
        <tbody>
          <tr>
            <td colspan="4" class="text-center border-0">
              <h5 class="m-0">放款审批申请表</h5>
            </td>
          </tr>
          <tr>
            <td>客户名称</td>
            <td>{{ related.customer_name }}</td>
            <td>客户类型</td>
            <td>{{ orgClassName }}</td>
          </tr>
          <tr>
            <td>担保额度</td>
            <td>{{ entrustContract.reply_funds || '' }}万元</td>
            <td>担保期限</td>
            <td>{{ entrustContract.load_years }}月</td>
          </tr>
          <tr>
            <td>担保费率</td>
            <td>{{ entrustContract.gua_rate || '-' }}%</td>
            <td>合同期间</td>
            <td>{{ loadPeriod }}</td>
          </tr>
          <tr>
            <td>放款机构</td>
            <td>{{ entrustContract.bank_name || '-' }}</td>
            <td>放款利率</td>
            <td>{{ entrustContract.load_rate || '-' }}%</td>
          </tr>
          <tr>
            <td>本次放款金额</td>
            <td>{{ entrustContract.reply_funds || '-' }}</td>
            <td>累计放款金额</td>
            <td>{{ entrustContract.reply_funds || '' }}</td>
          </tr>
          <tr>
            <td>反担保方案落实情况</td>
            <td colspan="3" class="text-left" :class="tdClass">
              <div v-if="!editable" class="text-indent">{{ approval.gua_method_impl }}</div>
              <el-input
                v-else
                v-model="editData.gua_method_impl"
                :rows="5"
                type="textarea"
                placeholder="反担保方案落实情况"
              ></el-input>
            </td>
          </tr>
          <tr>
            <td>业务落实情况</td>
            <td colspan="3" class="text-left" :class="tdClass">
              <div v-if="!editable" class="text-indent px-4 py-2">
                客户资料已按要求进行收集,相关合同已签署。已缴纳担保费
                <span class="text-decoration px-1">{{ approval.pay_gua_fee || '-' }}</span>
                元。 同意办理。
              </div>
              <div v-else class="d-flex align-items-center px-4 mx-4">
                <div>客户资料已按要求进行收集,相关合同已签署。已缴纳担保费</div>
                <el-input
                  class="text-decoration"
                  placeholder="已缴担保费"
                  v-model="editData.pay_gua_fee"
                ></el-input>
                <div>元。 同意办理。</div>
              </div>
              <div class="d-flex justify-content-between px-4">
                <div class="flex-1">农业担保部项目经理A角： {{ related.res_a_name }}</div>
                <div class="flex-1">农业担保部项目经理B角： {{ related.res_b_name }}</div>
              </div>
            </td>
          </tr>
          <tr v-if="!viewMode">
            <td>附件资料</td>
            <td colspan="3" class="text-left">
              <div
                class="d-flex justify-content-between align-items-center"
                v-for="(p, key) of enumAttach"
                :key="key"
              >
                <div class="flex-2 pl-2">{{ key }}、{{ p.label }}</div>
                <div class="flex-2">
                  <span>{{ +key === 3 ? '当前状态' : '有无附件' }}</span>
                  <small>({{ p.must ? '必填' : '非必填' }})</small>
                  :
                  <small :class="p.status ? 'text-success' : 'text-danger'">
                    {{ p.statusLabel }}
                  </small>
                </div>
                <div class="flex-1">
                  <el-button type="text" @click="handleAttach(p)">
                    <i :class="`fa fa-${resEditable ? 'gavel' : 'search'}`"></i>
                  </el-button>
                </div>
              </div>
            </td>
          </tr>
          <slot></slot>
        </tbody>
      </table>
      <div class="text-center" v-if="resEditable">
        <el-button
          type="primary"
          class="btn-long"
          :disabled="loading"
          :loading="saveLoading"
          @click="handleSuccessConfirm"
        >
          提交
        </el-button>
        <el-button
          class="btn-long"
          :disabled="loading"
          :loading="saveLoading"
          @click="handleDismiss"
        >
          取消
        </el-button>
      </div>
    </div>
    <contract-attachment
      :visible.sync="attachVisible"
      @success="refesAttach"
      :view-mode="!editable"
      :query-id="queryId"
      :must="attachMust && !!approvalId"
      :attach-name="attachType"
      :attach-data="attachList"
    ></contract-attachment>
  </div>
</template>

<script>
// import { printA4 } from '@vimi/utils-tool'
import {
  getRelated,
  getAuthPerson,
} from '@/credit/views/county/unionProvince/components/contractApprove/index'
import {
  getApproval,
  getAttachment,
  updateApproval,
  addApproval,
  getApprovalNoEdit,
  // countyCorpEdit,
  countyResAEdit,
  sendNotice,
} from '@/credit/views/county/unionProvince/components/loanApprove/index'
import { mapGetters } from 'vuex'
import ContractAttachment from '@/credit/views/city/self/components/contractRegistr/ContractAttachment'
export default {
  components: {
    ContractAttachment,
  },
  props: {
    viewMode: {
      type: Boolean,
      default: false,
    },
    queryId: String,
  },
  data() {
    return {
      loading: false,
      related: {},
      approval: {},
      editData: {
        gua_method_impl: '',
        pay_gua_fee: '',
        res_corp_option: '',
      },
      enumAttach: {},
      attachName: ['签约现场', '合同附件', '保费缴纳凭证'],
      attachList: [],
      attachVisible: false,
      attachType: '',
      saveLoading: false,
      attachMust: false,
      authPerson: {},
      riskManager: {},
    }
  },
  watch: {
    queryId: {
      handler: function () {
        this.getData()
        this.$store.dispatch('getEnumOrgClass')
      },
      immediate: true,
    },
  },
  computed: {
    ...mapGetters(['userId', 'user', 'entrustContract', 'enumOrgClassObj']),
    userName() {
      return this.user.realName
    },
    loadPeriod() {
      return (
        (this.entrustContract.load_date || '- ') +
        '至' +
        (this.entrustContract.load_end_date || ' -')
      )
    },
    // 客户类型
    orgClassName() {
      return this.enumOrgClassObj[this.related.org_class] || ''
    },

    approvalId() {
      return this.approval.loan_approval_id
    },
    editable() {
      // 需要区县端项目经理， 有权审批人审批后流转到审批中
      return !this.viewMode && getApprovalNoEdit(this.related, this.authPerson, this.user)
    },
    resEditable() {
      return !this.viewMode && countyResAEdit(this.related, this.user)
    },
    // corpEditable() {
    //   return !this.viewMode && countyCorpEdit(this.related, this.authPerson, this.user)
    // },
    // corpView() {
    //   return this.corpEditable || +this.related.loan_approval_status > 0
    // },
    tdClass() {
      return this.editable ? 'input-td' : ''
    },
  },

  created() {},
  methods: {
    handleSuccessConfirm() {
      const valid = this.validateContract()
      if (!valid) return

      this.$utils
        .msgbox({
          message: '是否提交？',
          type: 'warning',
          beforeClose: () => this.postApproval(),
        })
        .then(res => {
          this.$message.success('提交成功')
          this.$emit('success', res)
        })
        .catch(() => this.$message.error(`保存失败，请重试！`))
    },
    postApproval() {
      this.saveLoading = true
      return this.updataApproval().finally(() => {
        sendNotice(this.related, this.entrustContract)
        this.saveLoading = false
      })
    },
    getEditData() {
      return this.editData
    },
    updataApproval() {
      // 修改
      this.editData.res_a_status = 1
      this.editData.add_up_reply_funds = this.entrustContract.reply_funds
      this.editData.current_reply_funds = this.entrustContract.reply_funds
      this.editData.customer_related_id = this.queryId
      if (this.approvalId) {
        return updateApproval(this.approvalId, this.editData)
      }
      // 添加
      return addApproval({
        ...this.editData,
        res_b_person: this.related.res_b_name,
        res_a_person: this.userName,
        res_a_date: this.$utils.dateFormat(new Date(), 'yyyy-MM-dd hh:mm:ss'),
        service_id: this.related.service_id,
        recommend_service: this.related.recommend_service,
      })
    },
    getAuthPerson() {
      if (this.authPerson.userId) {
        return Promise.resolve()
      }

      return getAuthPerson().then(({ corp, riskManager }) => {
        this.authPerson = corp
        this.riskManager = riskManager
      })
    },
    // 提交验证
    validateContract() {
      const enumValid = {
        gua_method_impl: '请输入反担保方案落实情况',
        pay_gua_fee: '请输入已缴担保费',
      }

      const keys = Object.keys(enumValid)
      for (const key of keys) {
        if (!this.editData[key]) {
          this.$message.error(enumValid[key])
          return false
        }
      }
      const attach = this.enumAttach[3] || {}
      if (+attach.status !== 1) {
        this.$message.error('请上传保费缴纳凭证')
        return false
      }

      return true
    },
    handleDismiss() {
      this.$emit('dismiss', false)
    },
    getData() {
      const { queryId } = this
      if (!queryId) {
        return
      }
      this.loading = true
      return Promise.all([
        getRelated(queryId),
        getApproval(queryId),
        getAttachment(queryId, this.attachName),
        this.getAuthPerson(),
        this.$store.dispatch('getEntrustContract', queryId),
      ])
        .then(([related, approval, attachMent]) => {
          this.related = related
          this.approval = approval
          this.related.loanApprovalStatus = approval.res_a_status
          Object.keys(this.editData).forEach(key => {
            this.editData[key] = this.approval[key]
          })
          this.enumAttach = this.getAttachArray(attachMent)
          this.$emit('get-data', {
            related,
            approval,
            authPerson: this.authPerson,
            riskManager: this.riskManager,
          })
        })
        .finally(() => {
          this.loading = false
        })
    },
    refesAttach() {
      getAttachment(this.queryId, this.attachName).then(res => {
        this.enumAttach = this.getAttachArray(res)
      })
    },
    handleAttach(p) {
      this.attachMust = p.must
      this.attachType = p.attachName
      this.attachList = p.data
      this.attachVisible = true
    },
    getAttachArray(images) {
      const signImages = images.filter(item => item.attachment_type === this.attachName[0]) || []
      const contractImages =
        images.filter(item => item.attachment_type === this.attachName[1]) || []
      const feeImages = images.filter(item => item.attachment_type === this.attachName[2]) || []
      return {
        1: {
          attachName: this.attachName[0],
          label: '签约现场照片',
          status: signImages.length ? 1 : 0,
          statusLabel: signImages.length ? '有' : '无',
          data: signImages,
          must: false,
        },
        2: {
          attachName: this.attachName[1],
          label: '合同附件扫描',
          status: contractImages.length ? 1 : 0,
          statusLabel: contractImages.length ? '有' : '无',
          data: contractImages,
          must: false,
        },
        3: {
          attachName: this.attachName[2],
          label: '保费缴纳凭证',
          status: feeImages.length ? 1 : 0,
          statusLabel: feeImages.length ? '已上传' : '未上传',
          data: feeImages,
          must: true,
        },
      }
    },
  },
}
</script>
<style lang="scss" scoped>
.vertical-align-middle td {
  vertical-align: middle;
}
.input-td {
  background-color: #ffe;
}
.text-indent {
  text-indent: 2rem;
}
.text-decoration {
  border-bottom: 1px solid gray;
  width: 100px;
  padding: 0;
}
.flex-2 {
  flex: 2;
}
.option {
  min-height: 5rem;
}
</style>
